﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace RMM.FrameWork
{
    public static class CommonHelper
    {
        /// <summary>
        /// 检查是否为空和-999
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static bool Check(int? num)
        {
            if (!num.HasValue)
            {
                return false;
            }
            if (num.Value == -999)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检查是否为空和-999
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static bool Check(double? num)
        {
            if (!num.HasValue)
            {
                return false;
            }
            if (num.Value == -999)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检查是否为空和-999
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static bool Check(decimal? num)
        {
            if (!num.HasValue)
            {
                return false;
            }
            if (num.Value == -999)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检查是否为空和-999
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static bool Check(long? num)
        {
            if (!num.HasValue)
            {
                return false;
            }
            if (num.Value == -999)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检查字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool Check(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return false;
            }
            return true;
        }


        /// <summary>
        /// 检查字符串
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        public static bool Check(List<string> strList)
        {
            if (strList == null)
            {
                return false;
            }
            if (strList.Any(p => string.IsNullOrWhiteSpace(p)))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检查时间
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static bool Check(DateTime? num)
        {
            if (!num.HasValue)
            {
                return false;
            }
            return true;
        }

        public static bool Check(HttpCookie cookie)
        {
            if (cookie == null)
            {
                return false;
            }
            return true;
        }

        public static bool Check(bool b)
        {
            return b;
        }


        public static string GetStartDateStr(DateTime? d)
        {
            var str = string.Empty;
            if (d.HasValue)
            {
                str = d.Value.ToString("yyyy-MM-dd 00:00:00");
            }
            return str;
        }

        public static string GetEndDateStr(DateTime? d)
        {
            var str = string.Empty;
            if (d.HasValue)
            {
                str = d.Value.AddDays(1).ToString("yyyy-MM-dd 00:00:00");
            }
            return str;
        }



        public static async Task<T> PostAsync<T>(string url,dynamic postData) where T : class
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                HttpResponseMessage response = null;
                if (postData == null)
                {
                    response = await client.PostAsync(url, null);
                }
                else
                {
                    var str = new StringContent(JsonConvert.SerializeObject(postData), Encoding.UTF8, "application/json");
                    response = await client.PostAsync(url, str);
                }
                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<T>(responseJson);
                }
                return null;
            }
        }

        public static async Task<T> GetAsync<T>(string url) where T : class, new()
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<T>(responseJson);
                }
                return null;
            }
        }

        public static T Get<T>(string Url) where T : class, new()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return JsonConvert.DeserializeObject<T>(retString);
        }

        public static string GetServerIpv4()
        {
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;
        }


        /// <summary>
        /// 采用SHA-1算法加密字符串（小写）
        /// </summary>
        /// <param name="encypStr">需要加密的字符串</param>
        /// <returns></returns>
        public static string GetSha1(string encypStr)
        {
            var sha1 = SHA1.Create();
            var sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(encypStr));
            StringBuilder enText = new StringBuilder();
            foreach (var b in sha1Arr)
            {
                enText.AppendFormat("{0:x2}", b);
            }

            return enText.ToString();

            //byte[] strRes = Encoding.Default.GetBytes(encypStr);
            //HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
            //strRes = iSHA.ComputeHash(strRes);
            //StringBuilder enText = new StringBuilder();
            //foreach (byte iByte in strRes)
            //{
            //    enText.AppendFormat("{0:x2}", iByte);
            //}
        }

        /// <summary>
        /// 获取客户端IP地址（无视代理）
        /// </summary>
        /// <returns>若失败则返回回送地址</returns>
        public static string GetHostAddress()
        {
            string userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(userHostAddress))
            {
                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
            }
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.UserHostAddress;
            }

            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
            {
                return userHostAddress;
            }
            return "127.0.0.1";
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            if (string.IsNullOrEmpty(result))
            {
                return "0.0.0.0";
            }
            return result;
        }
    }
}
